package com.huluobo.h3weekdemo.main

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.huluobo.h3weekdemo.R
import com.huluobo.h3weekdemo.base.BaseMVVMFragment
import com.huluobo.h3weekdemo.databinding.FragmentTabBinding
import com.huluobo.h3weekdemo.db.AppDatabase
import com.huluobo.h3weekdemo.db.DatabaseUtil

class TabFragment : BaseMVVMFragment<FragmentTabBinding>() {

    private lateinit var viewModel: MainViewModel

    private val newsList = mutableListOf<NewsBean>()

    private lateinit var newsAdapter: NewsAdapter
    override fun getLayoutId(): Int = R.layout.fragment_tab

    override fun initData() {
        viewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]

        viewModel.typeId.observe(this) {
            viewModel.getNews(1, it, 10)
        }

        viewModel.getNewsSuccess.observe(this) { it ->
            if (it.code != -1) {
                newsList.clear()
                newsList.addAll(it.data)
                newsAdapter.notifyDataSetChanged()

                it.data.forEach {
                    DatabaseUtil.getDb().newsDao().insertNews(it)
                }
            }
        }

        viewModel.getNewsFailed.observe(this) {
            val queryNews = DatabaseUtil.getDb().newsDao().queryNews()
            newsList.clear()
            newsList.addAll(queryNews)
            newsAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        dataBinding.newsRv.layoutManager = LinearLayoutManager(requireActivity())
        newsAdapter = NewsAdapter(newsList)
        dataBinding.newsRv.adapter = newsAdapter
    }
}